<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>视频录制</title>
		<style type="text/css">
			.box {
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
			}
			video {
				margin-top: 50px;
			}
			.start-record {
				padding: 5px 20px;
				transition: 0.1s;
				border: 1px solid #3d81ff;
				color: #fff;
				background-color: #3d81ff;
				border-radius: 10px;
				font-weight: 600;
				font-size: 18px;
			}
			.start-record:active {
				opacity: 0.7;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<video style="min-width: 800px; min-height: 300px;max-width: 100%;"
			src="" controls="">
			</video>
			<hr/>
			<button class="start-record" type="button">开始录制</button>
		</div>
		<script>
			let btn = document.querySelector(".start-record");
			let video = document.querySelector("video");
			
			btn.addEventListener("click", async function() {
				// 录制的数据流
				let stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
				// 浏览器支持
				const mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" : "video/webm";
				let mediaRecoder = new MediaRecorder(stream, { mimeType: mime });
				
				let chunks = [];
				// 写入数据
				mediaRecoder.addEventListener("dataavailable", e => chunks.push(e.data));
				// 录制停止
				mediaRecoder.addEventListener("stop", () => {
					let blob = new Blob(chunks, {
						type: chunks[0].type
					});
					let url = URL.createObjectURL(blob);
					video.src = url;
					// 下载
					let a = document.createElement('a');
					a.href = url;
					a.download = 'video.webm';
					a.click();
				});
				
				// 手动启动
				mediaRecoder.start();
			});
		</script>
	</body>
</html>
